import Qt 4.7

import "priv.js" as P

Rectangle {

    id: root
    property real extent : 0    

    signal pause

    function decTime() {

	priv.leveltime -= 1
	if (priv.leveltime <= 0) {
	    death()

	}
    }
    function resumeTimers() {
	ftimer.running = true
	levelTimer.running = true

    }


    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Player {
        id: pl
        x: root.width / 2 - 20
        y: root.height - 20
        objectName: "player"
    }


    QtObject {
        id: priv

        property int sx: 0
        property int sy: 0

        property real vx: 0
        property real vy: 0

        property int score: 0
        property int accumScore: 20
	property int highscore: 0
        property int level : 0
        property int leveltime: 777
    }


    Rectangle {
        id: scoreboard
        z: 10

        Text {
            anchors {
                left: parent.left
                top: parent.top
            }

            id: sbHigh
            font.pixelSize: 20
            text:  "Hi: " + priv.highscore + " Lv: " + priv.level
        }
        Text {
            anchors {
                left : parent.left
                top: sbHigh.top
                leftMargin: 200

            }

            font.pixelSize: 30
            id: sbText
            text: priv.score
        }
    }

    Text {
        anchors {
            right: parent.right
            top: parent.top
            topMargin: 40
            rightMargin: 50
        }

        text: priv.leveltime


    }

    function levelCompleted() {
        console.log('level ok')
        resetScene()
        initializer.start()
        priv.level += 1
	priv.score+= 10 * priv.level
        info.show("Level " + priv.level)


    }

    function death() {
        //console.log("You die!")
        priv.level = 0
        resetScene()


        if (priv.score > priv.highscore) {
            priv.highscore  = priv.score
            info.show("!!! OMG! Highscore !!!")
	    engine.hiScore = priv.score
        } else {
            info.show("You die")
        }
        priv.leveltime = 777

        priv.score = 0

        initializer.start()

    }


    function collided(a,b) {
	//console.log('led',a,b)
        if (b.done) return
        b.collided()
        var sc = priv.accumScore
        showScore(b.x, b.y, sc)
        priv.accumScore += 5
        priv.score += sc
        var es = P.priv(root).enemies
        var found = false
        for (var i in es) {
            var e = es[i]
            if (!e.done) {
                found = true
                break
            }
        }

        if (!found) {
            levelCompleted()
        }


    }

    function resetScene() {
        ftimer.stop()
        engine.clearQmlObjects()
        var es = P.priv(root).enemies
        for (var i in es) {
            var e = es[i]
            e.destroy()

        }

        P.priv(root).enemies = []        

    }

    function setup() {
        engine.collision.connect(collided)
	priv.highscore = engine.hiScore
    }

    function createScene() {
        var enemies = []

        var co = Qt.createComponent("GoalObj.qml")
        for ( var i=0; i < 20; i++ ) {
            var c = co.createObject(root)

	    c.x = engine.randInt(1,root.width - 50)
            c.y = engine.randInt(1,root.height - 80)
            c.objectName = "enemy"
            //console.log(priv.enemies)
            enemies.push(c)
            c.z = levelTimer.z - 1
        }
	// used to be 30, too hard for tablet
	priv.leveltime = 40 - priv.level * 2

	if (priv.leveltime < 10) {
	    priv.leveltime = 10
	}

        pl.x = root.width / 2 - 20
        pl.y = root.height - 20


        engine.findQmlObjects()
        priv.vx = 0
        priv.vy = 0

        P.priv(root).enemies = enemies
        ftimer.start()
    }

    function showScore(x,y, score) {
        var co = Qt.createComponent("ScoreBouncer.qml")
        var o = co.createObject(root)
        o.start(x,y, score)
    }

    function doFrame() {
        pl.x += priv.vx
        pl.y += priv.vy
        //console.log(pl.x)
        priv.vx *= 0.98
        priv.vy *= 0.98
        engine.doFrame()
        if (pl.x < 0 && priv.vx < 0) {
            priv.vx = -priv.vx
        }
        if (pl.x + pl.width > root.width && priv.vx >0) {
            priv.vx = -priv.vx
        }

        if (pl.y < 0 && priv.vy < 0) {
            priv.vy = - priv.vy
        }
        if (pl.y + pl.height > root.height && priv.vy >0) {
            priv.vy = -priv.vy
        }


    }

    Timer {
        id: initializer
        onTriggered: {
            createScene()
        }
        running: false

    }


    Component.onCompleted: {
        setup()
        //createScene()
        initializer.start()
    }

    function calcRotation(sx, sy, ex, ey) {
        return Math.atan2(ey-sy, ex-sx) * 180/Math.PI;
    }

    Rectangle {
        id: spring
        property real sx
        property real sy
        property real ex
        property real ey

        function len() {
            var dx = (ex - sx)
            var dy = (ey - sy)
            return Math.sqrt( dx * dx  +
                                 dy * dy)

        }

        height: 3
        color: "blue"
        width: len()
        x: sx
        y: sy
        transformOrigin: Item.Left
        rotation: calcRotation(sx, sy, ex, ey)

    }

    InfoBanner {
        id: info
    }

    Image {
        id: catpaw
        source: "pic/tassu_4.png"
	x: root.width - 80
	y: root.height + 30
        z: 10

        Behavior on x {
            NumberAnimation { duration: 200 }
        }
        Behavior on y {
            NumberAnimation { duration: 200 }
        }

    }


    MouseArea {
        id: maMain
        onPressed: {
            priv.sx = mouse.x
            priv.sy = mouse.y
            spring.sx = mouse.x
            spring.sy = mouse.y
            //console.log("sx", sx, " sy", sy)
        }

        onPositionChanged:  {
            if (pressed) {
                spring.ex = mouse.x
                spring.ey = mouse.y

            }
        }

        onReleased: {

            var endx = mouse.x
            var endy = mouse.y
            var dx = (endx - priv.sx)
            var dy = (endy - priv.sy)
            var len = Math.sqrt( dx * dx  +
                                 dy * dy)

	    //console.log("Len = ", len)
            priv.vx = dx / 30
            priv.vy = dy / 30

            priv.accumScore = 5

	    //console.log("Len = ", len,  " p ", priv.vx, " ", priv.vy)

        }

        anchors.fill: parent

    }

    Item {

        anchors {
            left: parent.left
            bottom: parent.bottom
        }
        height: 50
        width: 50
        MouseArea {
            onClicked: {
		//console.log('click')
                ftimer.running = false
                levelTimer.running = false
                root.pause()
                mouse.accepted = true

            }
            anchors.fill: parent
        }

	Image {
	    source: "pic/media-playback-pause.png"
	    anchors.centerIn: parent
	}

    }

    states: [
        State {
            name: "prepare"
            when: maMain.pressed
            PropertyChanges {
                target: catpaw
                x: root.width - 100
                y: root.height - 150


            }
        }
    ]


}
